package com.tensquare.user.service;

import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

/**
 * @Author:zimmor
 * @Date: 2021/3/11 12:08
 * @Description
 * @version: 1.0.0
 */
@Service
@Transactional
public class UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 取消关注
     */
    public void cancelAttention(String userid, String friendid) {
        userDao.followCountReduce(userid);
        userDao.fanscountReduce(friendid);
    }

    /**
     * 关注某用户
     */
    public void followcountAdd(String userid, String friendid) {
        userDao.followcountAdd(userid);
        userDao.fanscountAdd(friendid);
    }

    /**
     * 发送验证码
     */
    public void sendMessage(String mobile) {
        Random random = new Random();
        int max = 999999;
        int min = 100000;
        int code = random.nextInt(max);
        Map<String, String> map = new HashMap<>();
        if(code < min) {
            code += min;
        }
        map.put("mobile",mobile);
        map.put("code",code+"");
        System.out.println(map.toString());
        rabbitTemplate.convertAndSend("message", map);
    }

    /**
     * 分页条件查询
     * @param user
     * @param page
     * @param size
     * @return
     */
    public Page<User> findSearch(User user ,int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if(user!=null && !"".equals(user.getNickname())) {
                    Predicate nickname = criteriaBuilder.like(root.get("nickname").as(String.class), "%" + user.getNickname() + "%");
                    list.add(nickname);
                }
                if(user!=null && !"".equals(user.getEmail())) {
                    Predicate email = criteriaBuilder.like(root.get("email").as(String.class), "%" + user.getEmail() + "%");
                    list.add(email);
                }
                Predicate[] predicates = list.toArray(new Predicate[list.size()]);
                return criteriaBuilder.and(predicates);
            }
        };
        return  userDao.findAll(specification, pageable);
    }

    /**
     * 根据条件查询
     * @param user
     * @return
     */
    public List<User> findSearch(User user) {
        return userDao.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if(user!=null && !"".equals(user.getNickname())) {
                    Predicate nickname = criteriaBuilder.like(root.get("nickname").as(String.class), "%" + "%");
                    list.add(nickname);
                }
                if (user!=null && !"".equals(user.getEmail())) {
                    Predicate email = criteriaBuilder.like(root.get("email").as(String.class), "%" + user.getEmail() + "%");
                    list.add(email);
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        });
    }

    public User findById(String id) {
        return userDao.findById(id).get();
    }

    /**
     * 新增数据
     * @param user
     */
    public void save(User user) {
        user.setId(idWorker.nextId()+"");
        userDao.save(user);
    }
    /**
     * 注册
     * @param user
     * @param code
     */
    public void register(User user, String code) {
        String syyCode = (String) redisTemplate.opsForValue().get("smsCode_"+user.getMobile());
        if (syyCode == null) {
            throw new RuntimeException("请先获取验证码");
        }
        if(!syyCode.equals(code)) {
            throw new RuntimeException("你的验证码错误");
        }
        user.setId( idWorker.nextId()+"" );
        user.setFollowcount(0);//关注数
        user.setFanscount(0);//粉丝数
        user.setOnline(0L);//在线时长
        user.setRegdate(new Date());//注册日期
        user.setUpdatedate(new Date());//更新日期
        user.setLastdate(new Date());//最后登陆日期
        userDao.save(user);
    }

    public void update(User user) {
        userDao.save(user);
    }

    public void delete(String id) {
        userDao.deleteById(id);
    }

    public List<User> findAll() {
        return userDao.findAll();
    }
}
